# encoding: UTF-8

'''
本文件包含了CTA引擎中的策略开发用模板，开发策略时需要继承CtaTemplate类。
'''

from base.ctaBase import *
from base.baseConstant import *
from datetime import datetime, timedelta

########################################################################
class CtaTemplate(object):
    """CTA策略模板"""
    
    # 策略类的名称和作者
    className = 'CtaTemplate'
    author = EMPTY_UNICODE
    
    # MongoDB数据库的名称，K线数据库默认为1分钟
    tickDbName = TICK_DB_NAME
    barDbName = MINUTE_DB_NAME
    
    # 策略的基本参数
    name = EMPTY_UNICODE           # 策略实例名称
    vtSymbol = EMPTY_STRING        # 交易的合约vt系统代码    
    
    # 策略的基本变量，由引擎管理
    inited = False                 # 是否进行了初始化
    trading = False                # 是否启动交易，由引擎管理, 
    pos = 0                        # 持仓情况
    
    # 策略Bar周期
    period = 30 #(分钟周期)
    # 历史周期数据
    hisBar = []
    hisBarOpen = []
    hisBarClose = []
    hisbarHigh = []
    hisBarLow = []

    hisDays = []
    hisTimes = []

    barMinute = ""
    barDateTime = datetime(1900, 1, 1, 1, 1, 1)
    barDay = ""
    
    #当前周期bar
    bar = None
    #rangeBar = None

    # 止损止盈
    isLimitProfit = False
    isLimitLose = False
    # 隔夜
    isPositionNextDat = False
    # 参数列表，保存了参数的名称
    paramList = ['name',
                 'className',
                 'author',
                 'vtSymbol',
                 'period',
                 'rangeBarInterval']
    
    # 变量列表，保存了变量的名称
    varList = ['inited',
               'trading',
               'pos']

    #----------------------------------------------------------------------
    def __init__(self, ctaEngine, setting):
        """Constructor"""
        self.ctaEngine = ctaEngine

        # 设置策略的参数
        if setting:
            d = self.__dict__
            for key in self.paramList:
                if key in setting:
                    d[key] = setting[key]
    
    #----------------------------------------------------------------------
    def onInit(self):
        """初始化策略（必须由用户继承实现）"""
        raise NotImplementedError
    
    #----------------------------------------------------------------------
    def onStart(self):
        """启动策略（必须由用户继承实现）"""
        raise NotImplementedError
    
    #----------------------------------------------------------------------
    def onStop(self):
        """停止策略（必须由用户继承实现）"""
        raise NotImplementedError

    #----------------------------------------------------------------------
    def onTick(self, tick):
        """收到行情TICK推送（必须由用户继承实现）"""

        if self.__dict__.has_key('rangeBarInterval'):
            self.onRangeBar(tick)
            return

        self.checkRisk(tick)
        #raise NotImplementedError
        #Date : 20160314  通用行情处理
        #TO-DO
        #非交易时间行情丢弃

        #TO-DO
        #检查tick交易信号

        #if not self.hisBar.has_key(self.period):
        #    self.hisBar = []

        tickMinute = tick.datetime.minute

        #if tick.date == '20160308':
        #    print tick.datetime

        #print tick.datetime , self.barDateTime
        if (self.barDateTime == "" ) or not ((tick.datetime < self.barDateTime) and (tick.datetime > (self.barDateTime - timedelta(minutes = self.period)))):
            if self.bar:
                self.hisBar.append(self.bar)
                self.hisBarOpen.append(self.bar.open)
                self.hisBarClose.append(self.bar.close)
                self.hisBarHigh.append(self.bar.high)
                self.hisBarLow.append(self.bar.low)

                self.onBar(self.bar)
                #self.bar = None
            bar = CtaBarData()
            bar.vtSymbol = tick.vtSymbol
            bar.symbol = tick.symbol
            bar.exchange = tick.exchange
            bar.open = tick.lastPrice
            bar.close = tick.lastPrice
            bar.low = tick.lastPrice
            bar.high = tick.lastPrice
            bar.date = tick.date
            bar.time = tick.time
            bar.datetime = datetime(tick.datetime.year, tick.datetime.month, tick.datetime.day, tick.datetime.hour, tick.datetime.minute, 0) + timedelta(minutes = self.period)
            bar.volume = tick.volume
            #bar.type = 0

            self.bar = bar
            self.barDateTime = bar.datetime
            self.barMinute = bar.time
        else:
            bar = self.bar
            #print bar, tick.datetime
            bar.high = max(bar.high, tick.lastPrice)
            bar.low = min(bar.low, tick.lastPrice)
            bar.close = tick.lastPrice
            bar.volume += tick.volume


        '''
        if not self.bar:
            bar = CtaBarData()
            bar.vtSymbol = tick.vtSymbol
            bar.symbol = tick.symbol
            bar.exchange = tick.exchange
            bar.open = tick.lastPrice
            bar.high = tick.lastPrice
            bar.low = tick.lastPrice
            bar.close = tick.lastPrice
            bar.date = tick.date
            bar.time = tick.time
            bar.datetime = datetime(tick.datetime.year, tick.datetime.month, tick.datetime.day, \
                            tick.datetime.hour, tick.datetime.minute, 0) + timedelta(minutes = self.period)
            bar.volume = tick.volume
            
            self.bar = bar
            self.barMinute = bar.time
            self.barDateTime = datetime.strptime(bar.date + ' ' + bar.time, '%Y%m%d %H:%M:%S')
            print "Bar :" + str(bar.datetime) +" " + str(tick.datetime)
            #print bar.date ,bar.time, bar.datetime, bar.datetime - timedelta(minutes=self.period)
            return 
        if (tick.datetime <= self.bar.datetime ) and (tick.datetime >= (self.bar.datetime - timedelta(minutes = self.period))):
            if tick.datetime >= datetime.strptime('20160308 091000', '%Y%m%d %H%M%S') and tick.datetime <= datetime.strptime('20160308 092100', '%Y%m%d %H%M%S'):
                print "update :" + str(self.bar.datetime) +" " + str(tick.datetime)
            bar = self.bar
            bar.high = max(bar.high, tick.lastPrice)
            bar.low = min(bar.low, tick.lastPrice)
            bar.close = tick.lastPrice
            bar.volume += tick.volume
            return


        print "Send :" + str(self.bar.datetime) +" " + str(tick.datetime)
        #产生bar事件
        if self.bar:
            self.hisBar.append(self.bar)
            self.hisBarOpen.append(self.bar.open)
            self.hisBarClose.append(self.bar.close)
            self.hisBarHigh.append(self.bar.high)
            self.hisBarLow.append(self.bar.low)

            self.onBar(self.bar)
            #self.hisDays.append(self.bar.date)
            self.bar = None

        '''

    #----------------------------------------------------------------------
    def onRangeBar(self, tick):
        """产生RangeBar"""

        if not self.bar or (tick.lastPrice > self.bar.upPrice or tick.lastPrice < self.bar.downPrice):
            if self.bar:
                #print self.bar.startDateTime, self.bar.barDateTime, self.bar, self.bar.upPrice, self.bar.downPrice
                self.hisBar.append(self.bar)
                self.hisBarOpen.append(self.bar.open)
                self.hisBarClose.append(self.bar.close)
                self.hisBarHigh.append(self.bar.high)
                self.hisBarLow.append(self.bar.low)
                self.onBar(self.bar)

            bar = CtaBarData()
            bar.vtSymbol = tick.vtSymbol
            bar.symbol = tick.symbol
            bar.exchange = tick.exchange

            bar.open = tick.lastPrice
            bar.high = tick.lastPrice
            bar.low = tick.lastPrice
            bar.close = tick.lastPrice

            bar.upPrice = tick.lastPrice + self.rangeBarInterval
            bar.downPrice = tick.lastPrice - self.rangeBarInterval
            #bar.type = 1

            bar.date = tick.date
            bar.time = tick.time
            bar.startDateTime = datetime.strptime(bar.date +' ' + bar.time, '%Y%m%d %H:%M:%S')
            bar.volume = tick.volume
            bar.barDateTime = bar.startDateTime
            bar.datetime = bar.startDateTime
            bar.hisTick = [tick.lastPrice]

            self.bar = bar
            #print "New Bar"

        else:
            
            bar = self.bar
            self.lastTick = tick
            self.lastBar = bar
            #print self.bar.barDateTime, self.bar, self.bar.upPrice, self.bar.downPrice
            bar.close = tick.lastPrice
            bar.high = min(max(bar.high, tick.lastPrice), bar.upPrice)
            bar.low = max(min(bar.low, tick.lastPrice), bar.downPrice)
            bar.volume += tick.volume
            bar.time = tick.time
            bar.barDateTime = datetime.strptime(bar.date +' ' + bar.time, '%Y%m%d %H:%M:%S')
            bar.hisTick.append(tick.lastPrice)



    #----------------------------------------------------------------------
    def onOrder(self, order):
        """收到委托变化推送（必须由用户继承实现）"""
        raise NotImplementedError
    
    #----------------------------------------------------------------------
    def onTrade(self, trade):
        """收到成交推送（必须由用户继承实现）"""
        raise NotImplementedError
    
    #----------------------------------------------------------------------
    def onBar(self, bar):
        """收到Bar推送（必须由用户继承实现）"""
        raise NotImplementedError
    
    #----------------------------------------------------------------------
    def buy(self, price, volume, stop=False):
        """买开"""
        return self.sendOrder(CTAORDER_BUY, price, volume, stop)
    
    #----------------------------------------------------------------------
    def sell(self, price, volume, stop=False):
        """卖平"""
        return self.sendOrder(CTAORDER_SELL, price, volume, stop)       

    #----------------------------------------------------------------------
    def short(self, price, volume, stop=False):
        """卖开"""
        return self.sendOrder(CTAORDER_SHORT, price, volume, stop)          
 
    #----------------------------------------------------------------------
    def cover(self, price, volume, stop=False):
        """买平"""
        return self.sendOrder(CTAORDER_COVER, price, volume, stop)
        
    #----------------------------------------------------------------------
    def sendOrder(self, orderType, price, volume, stop=False):
        """发送委托"""
        #print self.trading, stop
        if self.trading:
            # 如果stop为True，则意味着发本地停止单
            if stop:
                vtOrderID = self.ctaEngine.sendStopOrder(self.vtSymbol, orderType, price, volume, self)
            else:
                vtOrderID = self.ctaEngine.sendOrder(self.vtSymbol, orderType, price, volume, self) 
            return vtOrderID
        else:
            return None        
        
    #----------------------------------------------------------------------
    def cancelOrder(self, vtOrderID):
        """撤单"""
        if STOPORDERPREFIX in vtOrderID:
            self.ctaEngine.cancelStopOrder(vtOrderID)
        else:
            self.ctaEngine.cancelOrder(vtOrderID)
    
    #----------------------------------------------------------------------
    def getTotalPosition(self):
        """获取总持仓"""
        return self.ctaEngine.getTotalPosition(self.vtSymbol) 

    #----------------------------------------------------------------------
    def getLongPosition(self):
        """获取多头持仓"""
        return self.ctaEngine.getLongPosition(self.vtSymbol)

    #----------------------------------------------------------------------
    def getLongCostPrice(self):
        """获取多头持仓成本价"""
        return self.ctaEngine.getLongCostPrice(self.vtSymbol)
    #----------------------------------------------------------------------
    def getShortPosition(self):
        """获取空头持仓"""
        return self.ctaEngine.getShortPosition(self.vtSymbol)
    #----------------------------------------------------------------------
    def getShortCostPrice(self):
        """获取空头持仓成本价"""
        return self.ctaEngine.getShortCostPrice(self.vtSymbol)
    #----------------------------------------------------------------------
    def isFinishedOrders(self):
        """查询是否有委托未结束"""
        return self.ctaEngine.isFinishedOrders()
    #----------------------------------------------------------------------
    def insertTick(self, tick):
        """向数据库中插入tick数据"""
        self.ctaEngine.insertData(self.tickDbName, self.vtSymbol, tick)
    
    #----------------------------------------------------------------------
    def insertBar(self, bar):
        """向数据库中插入bar数据"""
        self.ctaEngine.insertData(self.barDbName, self.vtSymbol, bar)
        
    #----------------------------------------------------------------------
    def loadTick(self, days):
        """读取tick数据"""
        return self.ctaEngine.loadTick(self.tickDbName, self.vtSymbol, days)
    
    #----------------------------------------------------------------------
    def loadBar(self, days):
        """读取bar数据"""
        return self.ctaEngine.loadBar(self.barDbName, self.vtSymbol, days)
    
    #----------------------------------------------------------------------
    def checkRisk(self, tick):
        """检查风险"""
        
        #止盈止损
        #self.stopPosition(tick)

        pass

    def stopPosition(self, tick):
        """止盈止损"""
        floatingProfit = 0
        stopFlag = False


        if self.isFinishedOrders() and self.getTotalPosition() !=0:
             #多头持仓
             if self.getLongPosition() >0:
                 floatingProfit = int(self.getLongPosition()) * float(tick.lastPrice - self.getLongCostPrice())
             else:
                 floatingProfit = int(self.getShortPosition()) * float(tick.lastPrice - self.getShortCostPrice())


        if self.__dict__.has_key('fixStopProfit'):
                stopFlag = stopFlag or floatingProfit > self.fixStopProfit
        if self.__dict__.has_key('fixStopLoss'):
                stopFlag = stopFlag or floatingProfit < self.fixStopLoss

        #平仓
        if stopFlag:
            if self.getLongPosition() > 0:
                self.sell(tick.lastPrice - self.ctaEngine.slippage, self.getLongPosition())
            if self.getShortPosition() > 0:
                self.cover(tick.lastPrice + self.ctaEngine.slippage, self.getShortPosition())


    #----------------------------------------------------------------------
    def writeCtaLog(self, content):
        """记录CTA日志"""
        content = self.name + ':' + content
        self.ctaEngine.writeCtaLog(content)
        
    #----------------------------------------------------------------------
    def putEvent(self):
        """发出策略状态变化事件"""
        self.ctaEngine.putStrategyEvent(self.name)
    

